package com.mz3co.sysadmin.security;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.mz3co.sysadmin.service.SysAuthenticationInfoService;
import com.mz3co.sysadmin.service.SysUsersService;
import com.mz3co.sysadmin.model.SysAuthenticationInfo;
import com.mz3co.sysadmin.model.SysUsers;

public class MyAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

//	private static final String MERCHANTID = "merchantId";
	private static final String USERNAME = "username";
	private static final String PASSWORD = "password";
	private static final String RANDOMCODE = "randomCode";
//	private static final String TYPE = "type";
	
	@Autowired
	private SysUsersService sysUserService;
		
	@Autowired
	private SysAuthenticationInfoService authenticationInfoService;
	

	//*****************************************************************************************
	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)  throws AuthenticationException {
		
	    if (!request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
		}
		
	    response.setContentType("text/html;charset=utf-8");
	    
		String username = obtainUsername(request);
		String password = obtainPassword(request);
		String randomCode = obtainRandomcode(request);
		
		//获取保存在session中的验证
		HttpSession session = request.getSession();

		username = username.trim();

	    List<SysAuthenticationInfo> authInfoList = authenticationInfoService.getAuthenticationInfo(username, password);//authenticationInfoMapper.selectByExample(example);
	    
	    
	    SysUsers user = null;
	    
	    if (authInfoList == null ||authInfoList.isEmpty() ) {
			BadCredentialsException exception = new BadCredentialsException("用户名或密码错误！");
			throw exception;
		}
	    
	    user = sysUserService.getUsers(authInfoList.get(0).getUid().intValue());
	   
	    request.setAttribute("loginingAccount",authInfoList.get(0).getAccount() );
	    request.getSession().setAttribute("sysUser", user);
	    
		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(user.getId(), "123456"/*MD5Encoder.getMD5Str(password)*/);
		
		setDetails(request, authRequest);
		
		this.updateLoginLog(authInfoList.get(0), user,getRemortIP(request));
		
		return this.getAuthenticationManager().authenticate(authRequest);
	}	
	

	private void updateLoginLog(SysAuthenticationInfo authInfo,SysUsers user,String ip){
//		SysAuthenticationInfo authInfo=new SysAuthenticationInfo();
		authInfo.setId(authInfo.getId());
		authInfo.setLastIp(ip);
		authInfo.setLastTime(new Date());
		
		
		user.setId(user.getId());
    	user.setLastLoginIp(ip);
    	user.setLastLoginTime(new Date());
    	
    	
		authenticationInfoService.update(authInfo);
		
		sysUserService.update(user);
	}
	
	@Override
	protected String obtainUsername(HttpServletRequest request) {
		Object obj = request.getParameter(USERNAME);
		return null == obj ? "" : obj.toString();
	}

	@Override
	protected String obtainPassword(HttpServletRequest request) {
		Object obj = request.getParameter(PASSWORD);
		return null == obj ? "" : obj.toString();
	}
	
	protected String obtainRandomcode(HttpServletRequest request) {
		Object obj = request.getParameter(RANDOMCODE);
		return null == obj ? "" : obj.toString();
	}
	
	
//	protected String obtainType(HttpServletRequest request) {
//		Object obj = request.getParameter(TYPE);
//		return null == obj ? "" : obj.toString();
//	}
	
	@Override
	protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
		super.setDetails(request, authRequest);
		return;
	}
	
	//获得经过代理的IP
	public String getRemortIP(HttpServletRequest request) {  
		if (request.getHeader("x-forwarded-for") == null) {  
			return request.getRemoteAddr();  
		}  
		return request.getHeader("x-forwarded-for");  
	} 

	
}
